package db

import (
	"database/sql/driver"
	"fmt"
)

type BitBool bool

// 实现 sql.Scanner 接口，用于从数据库读取
func (b *BitBool) Scan(value interface{}) error {
	var i int64
	if err := scanInt(&i, value); err != nil {
		return err
	}
	*b = BitBool(i != 0)
	return nil
}

// 实现 driver.Valuer 接口，用于写入数据库
func (b *BitBool) Value() (driver.Value, error) {
	if b != nil && *b == true {
		return int64(1), nil
	}
	return int64(0), nil
}

// 辅助函数，支持多种整数类型
func scanInt(target *int64, value interface{}) error {
	switch v := value.(type) {
	case int:
		*target = int64(v)
	case int64:
		*target = v
	case int32:
		*target = int64(v)
	case int16:
		*target = int64(v)
	case int8:
		*target = int64(v)
	case uint:
		*target = int64(v)
	case uint64:
		*target = int64(v)
	case uint32:
		*target = int64(v)
	case uint16:
		*target = int64(v)
	case uint8:
		*target = int64(v)
	case nil:
		*target = 0
	default:
		return fmt.Errorf("unsupported type for conversion to int: %T", value)
	}
	return nil
}
